package com;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Transaction;
import com.google.appengine.api.datastore.Query.FilterOperator;

import struct.CommentInfo;
import struct.ItemInfo;
import struct.SellerInfo;

import java.sql.Date;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
import java.util.List;

@SuppressWarnings("serial")
public class ShowSellerAuctionServlet extends HttpServlet 
{//client-server style (get input from client, then redirect output)
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException, ServletException 
	{
		String username = req.getParameter("username");
		
		req.setAttribute("username", username);
		req.setAttribute("itemList", GetItemInfo(username));
		
		
		
		req.getRequestDispatcher("yourAuctions.jsp").forward(req, resp);
	}
	
	public ArrayList<ItemInfo> GetItemInfo(String username)
	{
		DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
		
		ArrayList<ItemInfo> list = new ArrayList<ItemInfo>();
		
		
		
		//get all auctions associated with this current user
		Query qAuctions = new Query("Auction").addFilter("SELLER", FilterOperator.EQUAL, username );
		Iterable<Entity> auctions = ds.prepare(qAuctions).asIterable();
		for(Entity auction : auctions )
		{
				ItemInfo item = new ItemInfo();
				String start = "";
				String end = "";
				String current="";
				java.util.Date d1,d2,d3;
				long minutes=-1;
				long hours=-1;
				long days=-1;
				double currBid;
				
				DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm");
				
				java.util.Date currentDate = new java.util.Date();	
				current = df.format(currentDate);
				
			
				item.itemID = auction.getKey().getId();
				//System.out.println(item.itemID);

				item.description = (String) auction.getProperty("DESCRIPTION");
				
				
				//get highest bid 
				Query qBids = new Query("Bid").addFilter("ITEMID", FilterOperator.EQUAL, Long.toString(item.itemID) );
				Iterable<Entity> bids = ds.prepare(qBids).asIterable();
				double maxBid = Double.parseDouble(auction.getProperty("PRICE").toString());
				for(Entity bid : bids )
				{
					currBid = (Double) bid.getProperty("OFFER");
					if(currBid > maxBid){
						maxBid = currBid;
					}
				}
				item.currentBid = maxBid;
				
				item.itemName = (String) auction.getProperty("NAME");
				//System.out.println(item.itemName);
				
				
				start =  (String) auction.getProperty("START");
				end =  (String) auction.getProperty("END");
				try {
					
					
					d1 = df.parse(start);
					d2 = df.parse(end);
					d3 = df.parse(current);
					
					if(d3.before(d1)){
						minutes = (d2.getTime()-d1.getTime())/(1000*60)%60;
						hours = (d2.getTime()-d1.getTime())/(1000*60*60)%24;
						days = (d2.getTime()-d1.getTime())/(1000*60*60*24);
						item.timeLeft = (days + "d" + hours + "h" +minutes+"m");
						item.showCancel=true;
					}else if (d3.after(d2)){
						try {
							
							for (int j = 0; j < 10; j++) {
								Transaction tx = ds.beginTransaction();
								try {
									Entity e = ds.get(KeyFactory.createKey("Auction", item.itemID));
									System.out.println("found"+e.getKey().toString()+"found");	
									ds.delete(tx, e.getKey());
									tx.commit();
									break;
									
								} catch (ConcurrentModificationException ed) {
									// continue
								} finally {
									if (tx.isActive())
										tx.rollback();
								}
							}
							
						} catch (EntityNotFoundException e) {
						}
						
						item.timeLeft = ("Expired");
						item.showCancel=false;
					}else{
						minutes = (d2.getTime()-d3.getTime())/(1000*60)%60;
						hours = (d2.getTime()-d3.getTime())/(1000*60*60)%24;
						days = (d2.getTime()-d3.getTime())/(1000*60*60*24);
						item.timeLeft = (days + "d" + hours + "h" +minutes+"m");
						item.showCancel=true;
					}
					
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				
	
				item.img = "ta1.jpg";
				item.seller = (String) auction.getProperty("SELLER");
				
				if(item.showCancel){
					list.add(item);
				}
			//}
		}
								
		return list;
	}
		
}
